//
//  WXSAudioEditor.m
//  SmartRecorderTest
//
//  Created by 王勇 on 16/9/13.
//  Copyright © 2016年 王勇. All rights reserved.
//

#import "WXSAudioEditor.h"
//#import "WXSAudioEditor.h"
#import <CoreMedia/CoreMedia.h>



@implementation WXSAudioEditor

+ (instancetype)shareAudioEdit
{
    static WXSAudioEditor *WXSAudioEditor;
    static dispatch_once_t once;
    
    dispatch_once(&once, ^{
        
        WXSAudioEditor = [[self alloc]init];
        
    });
        
    return WXSAudioEditor;
}

// 支持音频:m4a  视频:mp4
-(void)editAudiofileAtPath:(NSString *)filePath exportPath:(NSString *)exportPath WithTimeRanges:(NSArray<WXSDreamTalkModel *> *)timeRanges currentIndex:(NSInteger)index completionHandler:(success)handler{
    _block = handler;
    
    NSString *presetName;
    NSString *outputFileType;
    
    if ([filePath.lastPathComponent containsString:@"mp4"]) {
        
        presetName = AVAssetExportPreset1280x720;
        outputFileType = AVFileTypeMPEG4;
        
    }else if ([filePath.lastPathComponent containsString:@".caf"]){
        
        presetName = AVAssetExportPresetAppleM4A;
        outputFileType = AVFileTypeAppleM4A;
    }
    
    else{
        
        _block(NO);
        return;
    }
    
    // 拿到预处理音频文件
    NSURL *songURL = [NSURL fileURLWithPath:filePath];
    AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL:songURL options:nil];
    
//    NSError *assetError;
//    NSURL *exportURL = [NSURL fileURLWithPath:exportPath];
//    AVAssetWriter *assetWriter = [AVAssetWriter assetWriterWithURL:exportURL
//                                                          fileType:AVFileTypeAppleM4A
//                      //    if (assetError) {
//        NSLog (@"创建文件失败 error: %@", assetError);
//        _block(NO);
//    }
//                                       error:&assetError];
    
    if (index == 0 || index == timeRanges.count) {//如果没有需要剪裁的片段，则直接返回
        _block(YES);
    }
    
    for (NSInteger i = index;i < timeRanges.count; i++) {
        
        // 3.创建音频输出会话
        AVAssetExportSession *exportSession = [AVAssetExportSession exportSessionWithAsset:songAsset
                                                                                presetName:presetName];
        if (![timeRanges[i] isKindOfClass:[WXSDreamTalkModel class]]) {
            NSLog(@"Error! No sleep talk time range model found!");
            return;
        }
        
        WXSDreamTalkModel *range = timeRanges[i];
        [self cutFileWithExportSession:exportSession outputFileType:outputFileType timeRange:range filePath:filePath exportPath:exportPath];
    }
}


#pragma mark - Private
-(void)cutFileWithExportSession:(AVAssetExportSession *)exportSession outputFileType:(NSString*)outputFileType timeRange:(WXSDreamTalkModel*)timeRange filePath:(NSString*)filePath exportPath:(NSString*)exportPath {
    NSTimeInterval beginTime = timeRange.beginTime;
    NSTimeInterval endTime = timeRange.endTime;
    CMTime _startTime = CMTimeMake(beginTime, 1);
    CMTime _stopTime = CMTimeMake(endTime, 1);
    CMTimeRange exportTimeRange = CMTimeRangeFromTimeToTime(_startTime, _stopTime);
    
    // 4.设置音频输出会话并执行
    static int i = 0;
    NSString *finalExportPath = [exportPath stringByAppendingPathComponent:[NSString stringWithFormat:@"sleepTalk_%d.caf",i]];
    exportSession.outputURL = [NSURL fileURLWithPath:finalExportPath];// output path
    i++;
    exportSession.outputFileType = outputFileType;// output file type AVFileTypeAppleM4A
    exportSession.timeRange = exportTimeRange;// trim time range
    
    timeRange.modelFilePath = finalExportPath;

    [exportSession exportAsynchronouslyWithCompletionHandler:^{
        
        if (AVAssetExportSessionStatusCompleted == exportSession.status) {
            
            NSLog(@"AVAssetExportSessionStatusCompleted");
            _block(YES);
            
        } else if (AVAssetExportSessionStatusFailed == exportSession.status) {
            
            NSLog(@"AVAssetExportSessionStatusFailed");
//            NSLog(@"Error description:%@",exportSession.error.localizedDescription);
            _block(NO);
            
        } else {
            
            NSLog(@"Export Session Status: %ld", (long)exportSession.status);
            _block(NO);
        }
    }];
}

@end

